var selectBuildPlatId = 0;
function getService(element) {
	var $e = $(element);
	var selected = $e.val();
	if ($e.prop('selectedIndex') == 0) {
		selected = null;
	}
	$.ajax({
		url : "/smarttest-frontstage/testAuto/getService.action",
		data : { name : selected },
		method : 'POST',
		async : false,
		error : function(response, error) {
			dialog('error', 'error' + response.status, 3000);
		},
		success : function(data) {
			if (data.status == "succ" && data.data) {
				$("#docker_service").empty();
				$("#docker_service").html(data.data);
				$('#docker_service').selectpicker('refresh');
			    $('#docker_service').selectpicker('render');
		     }
		}
	});
}

function getAllGroups(func) {
	$.ajax({
		url : "/smarttest-frontstage/testAuto/getAllGroups.action",
		data : { },
		method : 'POST',
		async : false,
		error : function(response, error) {
			dialog('error', 'error' + response.status, 3000);
		},
		success : function(data) {
			if (data.status == "succ" && data.data) {
				$("#docker_group").html(data.data);
				if (func) {
					func();
				}
		     }
		}
	});
}

var datatable;
/**
 * 加载接口自动化首页的table（bootstrap datatable）
 */
function convertDataTable () {
	datatable = $('#dt_basic').DataTable({
		 "dom": "<'row'<'col-md-6'l<'#toolbar'>><'col-md-6'f>r>" +
	        "t" +
	        "<'row'<'col-md-5 sm-center'i><'col-md-7 text-right sm-center'p>>",
       //是否查询框
       searching: true,
       //自动宽度
       "bAutoWidth":false,
//       //解决重新加载表格内容问题
       destroy:true,
       'bPaginate': true,
       "bRetrieve": true,
       //是否可排序
       "bSort": true,
       //有无进度条
       "bProcessing": true,
       "bStateSave": true,
       /*"serverSide": true,*/
       //ajax作为数据源
       "ajax": {
           "url": "/smarttest-frontstage/testAuto/getAllBuilds.action",
           "type": "POST",
           "data": function(){
        	   return {
        		   "group" : $("#docker_group").prop('selectedIndex') != 0 ? $("#docker_group").find("option:selected").val() : null,
        		   "service" : JSON.stringify($("#docker_service").val()),
        		   "testenv" : JSON.stringify($("#test_env").val()),
      		     "time" : JSON.stringify($("#reservationT").val()),
      		     "issuedstatus" : JSON.stringify($("#issuedPermission").val())
        	    }
           },
           "dataSrc": function ( response ) {  
        	      if(response != null){   
                      for(var i=0;i<response.data.length;i++){  
                    	  response.data[i].DT_RowId = "buildPlatform_"+response.data[i].id;  
                      }  
                  }
        	      return response.data;
        	    },
        	    /*"success": function (){ alert("Callback ran!"); },与dataSrc不能共用*/
			"error":function(){alert("服务器未正常响应，请重试");}
			
	},
	"aoColumnDefs": [
		{
	        targets: 3,
	        data: "testenv",
	        render: function (data, type, row, meta) {
	            var testenv;
	            if (data == 1) {
	            	testenv = 'test';
	            }
	            else if (data == 2) {
	            	testenv = '线上';
	      	   }
	             return testenv;
	        }
	    },
    {
        targets: 4,
        data: "autoresult",
        render: function (data, type, row, meta) {
            var autoresultstr;
            if (data == 0) {
            	autoresultstr = '<button type=\"button\" onclick=\"audit(1)\" class=\"btn btn-success\"><i class=\"ace-icon fa fa-search bigger-110\"></i><span class="bigger-110 no-text-shadow">PASS</span></button>';
            }
            else if (data == 1) {
            	autoresultstr = '<button type=\"button\" onclick=\"audit(1)\" class=\"btn btn-danger\"><i class=\"ace-icon fa fa-search bigger-110\"></i><span class="bigger-110 no-text-shadow">FAIL</span></button>';
      	   }
      	   else if (data == 2){
      		 autoresultstr = '<button type=\"button\" onclick=\"audit(1)\" class=\"btn btn-warning\"><i class=\"ace-icon fa fa-search bigger-110\"></i><span class="bigger-110 no-text-shadow">SKIP</span></button>'; 
      	   }
      	  else if (data == 4){
      		autoresultstr = '<span class="bigger-110 label label-sm label-info">RUNNING</span>'; 
     	   }
      	   else {
      		 autoresultstr = ""; 
      	   }
             return autoresultstr;
        }
    },
    {
        targets: 5,
        data: "manualresult",
        render: function (data, type, row, meta) {
        	 var manualresultstr;
             if (data == 0) {
            	 manualresultstr = '<button type="button" onclick="audit(1)" class="btn btn-success" data-toggle="modal" data-target="#manualReportModal" ><i class="ace-icon fa fa-search bigger-110"></i><span class="bigger-110 no-text-shadow">PASS</span></button>';
             }
             else if (data == 1) {
            	 manualresultstr = '<button type="button" onclick="audit(1)" class="btn btn-danger" data-toggle="modal" data-target="#manualReportModal" ><i class="ace-icon fa fa-search bigger-110"></i><span class="bigger-110 no-text-shadow">FAIL</span></button>';
       	   }
       	   else if (data == 2){
       		manualresultstr = '<button type="button" onclick="audit(1)" class="btn btn-warning" data-toggle="modal" data-target="#manualReportModal" ><i class="ace-icon fa fa-search bigger-110"></i><span class="bigger-110 no-text-shadow">SKIP</span></button>'; 
       	   }
       	  else {
       		  //data-toggle="modal"  这个表示这个是modal,点击后可以打开modal。配合data-target
       		manualresultstr = '<button type="button" class="btn"  data-toggle="modal" data-target="#manualReportModal" ><i class="ace-icon fa fa-plus bigger-110"></i><span class="bigger-110 no-text-shadow">添加</span></button>'; 
      	   }
              return manualresultstr;
        }
    },
    {
        targets: 6,
        data: "buildtime",
        render: function (data, type, row, meta) {
     	   var buildtime = data==null?"":new Date(parseInt(data)).Format("yyyy-MM-dd hh:mm:ss");
            return buildtime;
        }
    },
    {
        targets: 7,
        data: "issuedpermission",
        render: function (data, type, row, meta) {
     	   var issuestatus;
     	   if (data == 1) {
     		  issuestatus = '<span class="label label-sm label-success">已同意</span>';
     	   }
     	   else if (data == 2){
     		  issuestatus = '<span class="label label-sm label-danger">已拒绝</span>'; 
     	   }
     	   else {
     		  issuestatus = "<div><button type=\"button\" onclick=\"agreeIssue(this);\" class=\"btn btn-primary\"><i class=\"ace-icon fa fa-check bigger-110\"></i>同意</button>"
                                +"&nbsp;<button type=\"button\" onclick=\"rejectIssue(this);\" class=\"btn btn-warning\"><i class=\"ace-icon fa fa-ban bigger-110\"></i>拒绝</button>&nbsp;"
                                +"</div>"; 
     	   }
            return issuestatus;
        }
    },
		],
		//列及参数设置
       "columns": [
            { "data": "dgroup" },
			{ "data": "dservice" },
           { "data": "drelease" },
           { "data": "testenv" },
           { "data": "autoresult" },
           { "data": "manualresult" },
           { "data": "buildtime" },
           { "data": "issuedpermission" },
       ],
       //初始化完成回调函数
       initComplete:function(){
       },
       //"aaSorting": [[1, 'asc']],//排序
       "aLengthMenu": [[10, 20, 50, 100, -1], ['10', '20', '50','100', "所有"] // change per page values here
       ],
       "iDisplayLength": 10,
       "oLanguage": {
           "oAria": {
               "sSortAscending": " - click/return to sort ascending",
               "sSortDescending": " - click/return to sort descending"
           },
           "sProcessing": "玩命加载中...",
           "sLengthMenu": "显示 _MENU_ 记录",
           "sZeroRecords": "对不起，查询不到任何相关数据",
           "sEmptyTable": "未有相关数据",
           "sLoadingRecords": "正在加载数据-请等待...",
           "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录。",
           "sInfoEmpty": "当前显示0到0条，共0条记录",
           "sInfoFiltered": "（数据库中共为 _MAX_ 条记录）",
           "sSearch": "模糊查询：",
           "sUrl": "",
           //多语言配置文件，可将oLanguage的设置放在一个txt文件中，例：Javascript/datatable/dtCH.txt
           "oPaginate": {
               "sFirst": "首页",
               "sPrevious": " 上一页 ",
               "sNext": " 下一页 ",
               "sLast": " 尾页 "
           }
       },
       //多语言配置

	});
}

/**
 * 查询后的处理，刷新bootstarp table
 */
function searchSubmit(){
	   datatable.ajax.reload( function ( json ) {
		    //这里的json返回的是服务器的数据
		} );   
}

function submitManualReport(){
	var manualTestResult = $("#manualTestResult").find("option:selected").val();
	var manualCaseFile = $("#importManualCaseFile").val();
	var bugUrl = $("#BugUrl").val();
	dialog('loading','','');
	$.ajax({
		url : "/smarttest-frontstage/testAuto/updateManualReport.action",
		data : {"buildplatformId":parseInt(selectBuildPlatId.replaceAll("buildPlatform_","")),"testresult":manualTestResult, "casefile":manualCaseFile,"bugUrl":bugUrl },
		method : 'POST',
		async : false,
		error : function(response, error) {
			dialog('error', 'error' + response.status, 3000);
		},
		success : function(data) {
			if (data.status == "succ") {
				if (data.data == -1) {
					dialog('error', '数据库操作失败', 3000);
				}
				else {
					dialog('succ', 'success', 3000);
				}
				searchSubmit();
		     }
		}
	});
}
function editManualReport() {
	$("#manualCase_section").html('<label id="manual_case">请选择测试用例</label>'+
			'<form id="importManualCase" name="importManualCase" method="POST"'+
				'enctype="multipart/form-data">'+
				'<div class="pull-left global-search-box">'+
					'<input type="file" id="importManualCaseFile"  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv" name="fileUpload" value=""'+
						'size="20" onclick="$("#importManualCaseFile").val("");" onchange="mqUploadFile();"/>'+									
				'</div>'+									
			'</form>');
	$("#submitdiv").html('<button id="submitManualReport" type="submit" class="btn btn-primary btn-sm" data-dismiss="modal" onclick="submitManualReport();">提交</button><button type="submit" class="btn btn-sm btn-warning" data-dismiss="modal" >关闭</button>');
	$("#manualTestResult").removeAttr("disabled",true);
	$("#getManualCase").removeAttr("disabled");
	$("#BugUrl").removeAttr("disabled");
}
function getManualReport(buildplatformId) {
	$.ajax({
		url : "/smarttest-frontstage/testAuto/getManualReport.action",
		data : {"buildplatformId":buildplatformId},
		method : 'POST',
		async : false,
		error : function(response, error) {
			dialog('error', 'error' + response.status, 3000);
		},
		success : function(data) {
			if (data.status == "succ") {
				var d = data.data;
				if (d != null) {
					$("#manualCase_section").html('<label>测试用例</label><label class="input form-group has-feedback has-error"><input id="getManualCase" class="form-control" type="text" name="getManualCase" style="height: 30px !important;"></label>');
					$("#submitdiv").html('<button id="editManualReport" type="submit" class="btn btn-primary btn-sm" onclick="editManualReport();">编辑</button><button type="submit" class="btn btn-sm btn-warning" data-dismiss="modal" >关闭</button>');
					var resultInt = parseInt(d.result);
					if (resultInt == 0 || resultInt == 1 || resultInt == 2) {
						$("#manualTestResult").val(resultInt);
					}
					$("#manualTestResult").attr("disabled",true);
					$("#getManualCase").val(d.casefile);
					$("#getManualCase").attr("disabled",true);
					$("#BugUrl").val(d.bugadd);
					$("#BugUrl").attr("disabled",true);
				}
				else {
					$("#manualCase_section").html('<label id="manual_case">请选择测试用例</label>'+
							'<form id="importManualCase" name="importManualCase" method="POST"'+
								'enctype="multipart/form-data">'+
								'<div class="pull-left global-search-box">'+
									'<input type="file" id="importManualCaseFile"  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv" name="fileUpload" value=""'+
										'size="20" onclick="$("#importManualCaseFile").val("");" onchange="mqUploadFile();"/>'+									
								'</div>'+									
							'</form>');
					$("#submitdiv").html('<button id="submitManualReport" type="submit" class="btn btn-primary btn-sm" data-dismiss="modal" onclick="submitManualReport();">提交</button><button type="submit" class="btn btn-sm btn-warning" data-dismiss="modal" >取消</button>');
					$("#manualTestResult").val(0);
					$("#manualTestResult").removeAttr("disabled",true);
					$("#getManualCase").removeAttr("disabled");
					$("#BugUrl").val("");
					$("#BugUrl").removeAttr("disabled");
				}
		     }
		}
	});
}

function rejectIssue(e) {
	dialog('loading','','');
	$.ajax({
		url : "/smarttest-frontstage/testAuto/rejectIssue.action",
		data : {"buildplatformId":parseInt($(e).closest("tr").attr("id").replaceAll("buildPlatform_",""))},
		method : 'POST',
		async : false,
		error : function(response, error) {
			dialog('error', 'error' + response.status, 3000);
		},
		success : function(data) {
			if (data.status == "succ") {
				if (data.data == -1) {
					dialog('error', '数据库操作失败', 3000);
				}
				else if(data.data == 1){
					dialog('succ', 'success', 3000);
				}
				searchSubmit();
		     }
		}
	});
}

function agreeIssue(e) {
	dialog('loading','','');
	$.ajax({
		url : "/smarttest-frontstage/testAuto/agreeIssue.action",
		data : {"buildplatformId":parseInt($(e).closest("tr").attr("id").replaceAll("buildPlatform_",""))},
		method : 'POST',
		async : false,
		error : function(response, error) {
			dialog('error', 'error' + response.status, 3000);
		},
		success : function(data) {
			if (data.status == "succ") {
				if (data.data == -1) {
					dialog('error', '数据库操作失败', 3000);
				}
				else if(data.data == 1){
					dialog('succ', 'success', 3000);
				}
				searchSubmit();
		     }
		}
	});
}